package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{


    private StringRedisTemplate stringRedisTemplate;

    private static final String id= UUID.randomUUID().toString(true);
    private String opsName;
    private static final String KEY_PREFIX="lock:";

    public SimpleRedisLock(String opsName,StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.opsName = opsName;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String threadName=Thread.currentThread().getName();
        Boolean success = stringRedisTemplate.opsForValue().
                setIfAbsent(KEY_PREFIX + opsName, threadName+id, timeoutSec, TimeUnit.SECONDS);

        return (Boolean.TRUE.equals(success));


    }

    @Override
    public void unlock() {

        String threadNameWithID=Thread.currentThread().getName()+id;
        if(stringRedisTemplate.opsForValue().get(KEY_PREFIX + opsName).equals(threadNameWithID))
            stringRedisTemplate.delete(KEY_PREFIX + opsName);
    }
}
